<?php


namespace app\api\controller\xiluedu;


use app\common\controller\Api;
use app\common\model\ScoreLog;
use app\common\model\xiluedu\LotteryActive;
use app\common\model\xiluedu\LotteryLog;
use think\db\Expression;
use function fast\array_get;

class Lottery extends Api
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['*'];

    /**
     * 转盘活动列表
     */
    public function lottery(){
        $params = $this->request->param('');
        $this->success('查询成功',LotteryActive::lists($params));
    }

    /**
     * 抽奖活动详情
     */
    public function lottery_detail(){
        $params = $this->request->param('');
        $this->success('查询成功',LotteryActive::detail($params));
    }

    /**
     * 抽奖明细
     */
    public function lottery_log(){
        $params = $this->request->param('');
        $this->success('查询成功',LotteryLog::lists($params));
    }

    /**
     * 抽奖
     */
    public function go_lottery(){
        $params = $this->request->param('');
        $lottery_active_id = array_get($params,'lottery_active_id');
        if(!$lottery_active_id){
            $this->error('参数错误');
        }
        $lottery_active = LotteryActive::with(['lotteryAwards'])
            ->where('status',1)
            ->where('id',$lottery_active_id)
            ->find();
        $user = $this->auth->getUser();
        $lottery_log_count = LotteryLog::where('user_id',$user->id)->whereTime('createtime','d')->count();
        $surplus_count = $lottery_active->day_count - $lottery_log_count;
        if(!$lottery_active){
            $this->error('活动未找到');
        }
        if(time() < $lottery_active['start_time']){
            $this->error('活动未开始');
        }
        else if(time() > $lottery_active['end_time']){
            $this->error('活动已结束');
        }
        else if($surplus_count <= 0 && $user['score'] < $lottery_active['score']){
            $this->error('积分不足');
        }
        else{
            $arr = [];
            $lottery = [];
            $lotteryAwards = $lottery_active['lottery_awards'];
            foreach ($lotteryAwards as $key=>$val){
                $arr[$val['id']] = $val['rate'];
                $lottery[$val['id']] = $val;
            }
            $prize_id = $this->get_rand($arr);
            if(!$prize_id){
                $this->error('服务器异常');
            }

            $prize = $lottery[$prize_id];
            db()->startTrans();
            #抽奖日志
            $data = [
                'user_id'           =>  $user->id,
                'lottery_active_id' =>  $lottery_active_id,
                'lottery_id'        =>  $prize_id,
                'score'             =>  $prize->reward,
                'awards_name'       =>  $prize->name,
                'award_time'        =>  time()
            ];
            $result = LotteryLog::create($data);
            #积分消耗
            $score = 0;
            if($surplus_count <= 0){
                $score -= $lottery_active['score'];
                $log[] = [
                    'user_id'   =>  $user->id,
                    'score'     =>  '-'.$lottery_active['score'],
                    'before'    =>  $user->score,
                    'after'     =>  $user->score - $lottery_active['score'],
                    'memo'      =>  '抽奖消耗',
                    'createtime'=>  time(),
                ];
            }
            #获取积分
            if($prize->reward > 0){
                $score += $lottery_active['score'];
                $log[] = [
                    'user_id'   =>  $user->id,
                    'score'     =>  $lottery_active['score'],
                    'before'    =>  $surplus_count <=0 ? ($user->score - $lottery_active['score']) : $user->score,
                    'after'     =>  $surplus_count <=0 ? ($user->score - $lottery_active['score'] + $prize->reward) : $user->score +$prize->reward,
                    'memo'      =>  '抽奖获得积分',
                    'createtime'=>  time(),
                ];
            }
            $result2 = (new ScoreLog())->saveAll($log);
            $result3 = $user->score = new Expression("score+".$score);
            if($result !== false && $result2>0 && $result3 !== false){
                db()->commit();
                $this->success('抽奖成功',$prize);
            }else{
                db()->rollback();
                $this->error('抽奖失败');
            }

        }
    }

    //抽奖概率计算
    protected function get_rand($proArr) {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);

        return $result;
    }

}